package com.socialcoco.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 阿里云 OSS文件类
 */
@Component
@ConfigurationProperties(prefix = "ali")
public class AliOssCloudUtil {
    Log log = LogFactory.getLog(AliOssCloudUtil.class);
    private String endpoint= "oss-cn-beijing.aliyuncs.com";

    //阿里云的accessKeyId
    private String accessKeyId= "LTAI5t6Vi3NcCp9XyvVBcAKj";

    //阿里云的accessKeySecret
    private String accessKeySecret ="FOI7ozsnDZ44GqQBW1VvLPqszmXqCL";

    //空间
    private String bucketName="socialcoco";

    //文件存储目录
    private String filedir="user/";

    private OSSClient ossClient;

    public AliOssCloudUtil() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    public String getFiledir() {
        return this.filedir;
    }

    //自定义上传文件夹
    public AliOssCloudUtil(String filedir) {
        this.filedir = filedir;
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }


    /**
     * 初始化
     */
    public void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 销毁
     */
    public void destory() {
        ossClient.shutdown();
    }


    /**
     * 上传到OSS服务器
     *
     * @param file

     */
    public String uploadFile(MultipartFile  file) {
        ArrayList<String> urls = new ArrayList<>();

            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1)));
            objectMetadata.setHeader("x-oss-forbid-overwrite", "false");
            objectMetadata.setContentDisposition("inline");
            String ret = "";
            // 判断bucket是否已经存在,不存在进行创建

            try {
                //创建上传Object的Metadata
                //连接oss客户端
                OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                // 上传文件流
                InputStream inputStream = file.getInputStream();
                //根据时间拼接url
                String url = getFiledir()+System.currentTimeMillis()+file.getOriginalFilename();
                //上传
                ossClient.putObject(bucketName, url, inputStream,objectMetadata);
                // 关闭OSSClient。
                ossClient.shutdown();

                ret="https://"+bucketName+"."+endpoint+"/"+url;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }


        return ret;
    }


    /**
     * 判断文件是否存在。doesObjectExist还有一个参数isOnlyInOSS，
     * 如果为true则忽略302重定向或镜像；如果为false，则考虑302重定向或镜像。
     * yourObjectName 表示上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
     *
     * @return 存在返回true
     */
    public boolean doesObjectExist(String objectName) {
        boolean exists = ossClient.doesObjectExist(bucketName, filedir + objectName);
        return exists;
    }

    /**
     * 判断Bucket是否存在
     *
     * @return 存在返回true
     */
    public boolean doesBucketExist() {
        boolean exists = ossClient.doesBucketExist(bucketName);
        return exists;
    }

    /**
     * 创建Bucket
     */
    public void createBucket() {
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
        // 设置bucket权限为公共读，默认是私有读写
        createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
        // 设置bucket存储类型为低频访问类型，默认是标准类型
        createBucketRequest.setStorageClass(StorageClass.IA);
        boolean exists = ossClient.doesBucketExist(bucketName);
        if (!exists) {
            try {
                ossClient.createBucket(createBucketRequest);

                // 关闭client
//                ossClient.shutdown();
//                log.info("buzzh");
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if ("bmp".equalsIgnoreCase(FilenameExtension)) {
            return "image/bmp";
        }
        if ("gif".equalsIgnoreCase(FilenameExtension)) {
            return "text/plain";
        }
        if ("jpeg".equalsIgnoreCase(FilenameExtension) ||
                "jpg".equalsIgnoreCase(FilenameExtension) ||
                "png".equalsIgnoreCase(FilenameExtension)) {
            return "image/jpg";
        }
        if ("html".equalsIgnoreCase(FilenameExtension)) {
            return "text/html";
        }
        if ("txt".equalsIgnoreCase(FilenameExtension)) {
            return "text/plain";
        }
        if ("vsd".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.visio";
        }
        if ("pptx".equalsIgnoreCase(FilenameExtension) ||
                "ppt".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if ("docx".equalsIgnoreCase(FilenameExtension) ||
                "doc".equalsIgnoreCase(FilenameExtension)) {
            return "application/msword";
        }
        if ("xml".equalsIgnoreCase(FilenameExtension)) {
            return "text/xml";
        }
        return "image/jpeg";
    }


    /**
     * @param fileName
     * @return
     * @Title: getInputStreamByFileUrl
     * @Description: 根据文件路径获取InputStream流
     * @return: InputStream
     */
    public InputStream getInputStreamByFileUrl(String fileName) {
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, fileName);
        return ossObject.getObjectContent();
    }
}